package com.example.ymm.modules1.service.dd;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkrobot_1_0.Client;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendHeaders;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendRequest;
import com.aliyun.dingtalkrobot_1_0.models.OrgGroupSendResponse;
import com.aliyun.tea.TeaException;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiChatCreateRequest;
import com.dingtalk.api.request.OapiChatGetRequest;
import com.dingtalk.api.request.OapiChatUpdateRequest;
import com.dingtalk.api.response.OapiChatCreateResponse;
import com.dingtalk.api.response.OapiChatGetResponse;
import com.dingtalk.api.response.OapiChatUpdateResponse;
import com.example.ymm.exception.YmException;
import com.example.ymm.modules1.entity.my.user.DbChatGroup;
import com.example.ymm.modules1.service.dto.DbChatGroupDto;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * @author zeymo
 */
@Slf4j
@Service
public class RobotGroupMessagesService {
    private Client robotClient;
    private final AccessTokenService2 accessTokenService;

    @Value("${dd.robot_code}")
    private String robotCode;

    @Autowired
    public RobotGroupMessagesService(AccessTokenService2 accessTokenService) {
        this.accessTokenService = accessTokenService;
    }

    @PostConstruct
    public void init() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = "https";
        config.regionId = "central";
        robotClient = new Client(config);
    }

    /**
     * 发送 文本消息到群聊
     * send message to group with openConversationId
     *
     * @param openConversationId conversationId
     * @return messageId
     * @throws Exception e
     */
    public String send(String openConversationId, String text) throws Exception {
        OrgGroupSendHeaders orgGroupSendHeaders = new OrgGroupSendHeaders();
        orgGroupSendHeaders.setXAcsDingtalkAccessToken(accessTokenService.getAccessToken());

        OrgGroupSendRequest orgGroupSendRequest = new OrgGroupSendRequest();
        orgGroupSendRequest.setMsgKey("sampleText");
        orgGroupSendRequest.setRobotCode(robotCode);
        //System.out.println("--robotCode::"+robotCode);
        orgGroupSendRequest.setOpenConversationId(openConversationId);

        JSONObject msgParam = new JSONObject();
        msgParam.put("content", text);
        orgGroupSendRequest.setMsgParam(msgParam.toJSONString());
        try {
            OrgGroupSendResponse orgGroupSendResponse = robotClient.orgGroupSendWithOptions(orgGroupSendRequest,
                    orgGroupSendHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            if (Objects.isNull(orgGroupSendResponse) || Objects.isNull(orgGroupSendResponse.getBody())) {
                log.error("RobotGroupMessagesService_send orgGroupSendWithOptions return error, response={}",
                        orgGroupSendResponse);

                return null;
            }

            return orgGroupSendResponse.getBody().getProcessQueryKey();
        } catch (TeaException e) {
            log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw TeaException, errCode={}, " +
                    "errorMessage={}", e.getCode(), e.getMessage(), e);
            throw new YmException(e.getMessage());
           // throw e;
        } catch (Exception e) {
            log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw Exception", e);
            throw new YmException(e.getMessage());
            //throw e;
        }
    }



    /**
     * 发送 图片消息到群聊
     * send message to group with openConversationId
     *
     * @param openConversationId conversationId
     * @return messageId
     * @throws Exception e
     */
    public String sendImg(String openConversationId, String img) throws Exception {
        OrgGroupSendHeaders orgGroupSendHeaders = new OrgGroupSendHeaders();
        orgGroupSendHeaders.setXAcsDingtalkAccessToken(accessTokenService.getAccessToken());

        OrgGroupSendRequest orgGroupSendRequest = new OrgGroupSendRequest();
        orgGroupSendRequest.setMsgKey("sampleImageMsg");
        orgGroupSendRequest.setRobotCode(robotCode);
        //System.out.println("--robotCode::"+robotCode);
        orgGroupSendRequest.setOpenConversationId(openConversationId);

        JSONObject msgParam = new JSONObject();
        msgParam.put("photoURL", img);
        orgGroupSendRequest.setMsgParam(msgParam.toJSONString());
        try {
            OrgGroupSendResponse orgGroupSendResponse = robotClient.orgGroupSendWithOptions(orgGroupSendRequest,
                    orgGroupSendHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            if (Objects.isNull(orgGroupSendResponse) || Objects.isNull(orgGroupSendResponse.getBody())) {
                log.error("RobotGroupMessagesService_send orgGroupSendWithOptions return error, response={}",
                        orgGroupSendResponse);

                return null;
            }

            return orgGroupSendResponse.getBody().getProcessQueryKey();
        } catch (TeaException e) {
            log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw TeaException, errCode={}, " +
                    "errorMessage={}", e.getCode(), e.getMessage(), e);
            throw new YmException(e.getMessage());
            // throw e;
        } catch (Exception e) {
            log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw Exception", e);
            throw new YmException(e.getMessage());
            //throw e;
        }
    }


    /**
     * 发送小程序链接
     * @param openConversationId
     * @return
     * @throws Exception
     */
    public String sendLink(String openConversationId)throws Exception {
        OrgGroupSendHeaders orgGroupSendHeaders = new OrgGroupSendHeaders();
        orgGroupSendHeaders.setXAcsDingtalkAccessToken(accessTokenService.getAccessToken());

        OrgGroupSendRequest orgGroupSendRequest = new OrgGroupSendRequest();
        orgGroupSendRequest.setMsgKey("sampleActionCard");//sampleText sampleLink
        orgGroupSendRequest.setRobotCode(robotCode);
        //System.out.println("--robotCode::"+robotCode);
        orgGroupSendRequest.setOpenConversationId(openConversationId);

        JSONObject msgParam = new JSONObject();
        String text="点击该链接进入学习,或者 可在 手机钉钉>工作台>全员>读书打卡，找到读书打卡小程序进行读书打卡！";
//        msgParam.put("content", text);
        msgParam.put("text", text);
        msgParam.put("title", "读书打卡");
//        msgParam.put("picUrl", "https://i01.lw.aliimg.com/media/lALPD1za8xExJTTNB9DNB9A_2000_2000.png");
//        msgParam.put("messageUrl", "dingtalk://dingtalkclient/action/open_micro_app?corpId=ding2e2011827f67ec7d35c2f4657eb6378f&agentId=3136542690&miniAppId=5000000006010649&pVersion=1&packageType=1&page=pages/home/home");
        msgParam.put("singleTitle", "查看");
        msgParam.put("singleURL", "dingtalk://dingtalkclient/action/open_micro_app?corpId=ding2e2011827f67ec7d35c2f4657eb6378f&agentId=3136542690&miniAppId=5000000006010649&pVersion=1&packageType=1&page=pages/home/home");

        orgGroupSendRequest.setMsgParam(msgParam.toJSONString());
        try {
            OrgGroupSendResponse orgGroupSendResponse = robotClient.orgGroupSendWithOptions(orgGroupSendRequest,
                    orgGroupSendHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            if (Objects.isNull(orgGroupSendResponse) || Objects.isNull(orgGroupSendResponse.getBody())) {
                log.error("RobotGroupMessagesService_send orgGroupSendWithOptions return error, response={}",
                        orgGroupSendResponse);

                return null;
            }

            return orgGroupSendResponse.getBody().getProcessQueryKey();
        } catch (TeaException e) {
            log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw TeaException, errCode={}, " +
                    "errorMessage={}", e.getCode(), e.getMessage(), e);
            throw new YmException(e.getMessage());
            // throw e;
        } catch (Exception e) {
            log.error("RobotGroupMessagesService_send orgGroupSendWithOptions throw Exception", e);
            throw new YmException(e.getMessage());
            //throw e;
        }
    }

    /**
     * 创建群聊
     *
     * @return
     */
    public JSONObject createGroupChat(DbChatGroup group) {
        JSONObject json = null;
        JSONObject result = null;
        String access_token = accessTokenService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/create");
        OapiChatCreateRequest req = new OapiChatCreateRequest();
        req.setName(group.getName());
        req.setOwner(group.getOwner());
        req.setUseridlist(group.getUserIdLists());
        req.setShowHistoryType(1L);
        req.setSearchable(0L);
        req.setValidationType(0L);
        req.setMentionAllAuthority(0L);
        req.setManagementType(0L);
        req.setChatBannedType(0L);
        try {
            OapiChatCreateResponse rsp = client.execute(req, access_token);
            // System.out.println(rsp.getBody());
            json = JSONObject.parseObject(rsp.getBody());
            if ("0".equals(json.getString("errcode"))) {
                //   result=json.getJSONObject("result");
            } else {
                throw new YmException(json.getString("errmsg"));

            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new YmException(e.getMessage());
        }

        return json;
    }


    /**
     * 修改群聊
     *
     * @return
     */
    public JSONObject editGroupChat(DbChatGroupDto group) {
        JSONObject json = null;
        JSONObject result = null;
        String access_token = accessTokenService.getAccessToken();

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/update");
        OapiChatUpdateRequest req = new OapiChatUpdateRequest();
        req.setChatid(group.getChatid());
        if(UtilValidate.isNotEmpty(group.getName())) {
            req.setName(group.getName());
        }
        if(UtilValidate.isNotEmpty(group.getOwner())) {
            req.setOwner(group.getOwner());
        }
        if(UtilValidate.isNotEmpty(group.getAddUserIds())){
            String[] split = group.getAddUserIds().split(",");
            List<String> list = Arrays.asList(split);
            req.setAddUseridlist(list);
            if(UtilValidate.isNotEmpty(group.getUseridlist())){
                group.setUseridlist(group.getUseridlist()+","+group.getAddUserIds());
            }
        }
        if(UtilValidate.isNotEmpty(group.getDeleteUserIds())){
            String[] split = group.getDeleteUserIds().split(",");
            List<String> list = Arrays.asList(split);
            req.setDelUseridlist(list);
            if(UtilValidate.isNotEmpty(group.getUseridlist())){
                String s = group.getUseridlist().replaceAll(group.getDeleteUserIds(), "");
                group.setUseridlist(s);
            }
        }
//        req.setDelUseridlist(Arrays.asList("userid1"));
//        req.setAddExtidlist(Arrary.asList("userid1"));
//        req.setDelExtidlist(Arrary.asList("userid2"));
        req.setIsBan(false);
        req.setSearchable(1L);
//        req.setValidationType(0L);
//        req.setMentionAllAuthority(0L);
//        req.setManagementType(0L);
//        req.setChatBannedType(0L);
//        req.setShowHistoryType(0L);
        try {
            OapiChatUpdateResponse rsp = client.execute(req,access_token);
            // System.out.println(rsp.getBody());
            json = JSONObject.parseObject(rsp.getBody());
            if ("0".equals(json.getString("errcode"))) {
                //   result=json.getJSONObject("result");
            } else {
                throw new YmException(json.getString("errmsg"));

            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new YmException(e.getMessage());
        }

        return json;
    }


    /**
     * 查询群成员
     * chatid chatc43162d0a211d854870e635da2b37bc9
     *
     * @return
     */
    public JSONObject queryGroupChatUsers(String chatid) {
        JSONObject json = null;
        JSONObject result = null;
        String access_token = accessTokenService.getAccessToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/get");
        OapiChatGetRequest req = new OapiChatGetRequest();
        req.setChatid(chatid);
        req.setHttpMethod("GET");
        try {
            OapiChatGetResponse rsp = client.execute(req, access_token);
            json = JSONObject.parseObject(rsp.getBody());
            if ("0".equals(json.getString("errcode"))) {
                result = json.getJSONObject("chat_info");
            } else {
                throw new YmException(json.getString("errmsg"));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }

        return result;
    }


}
